/**
 * Created by stillyuk on 16/5/29.
 */

'use strict';

angular.module('app.plugin', [])
    .directive('myImagePreview', function ($compile) {
        return {
            restrict: 'A',
            scope: true,
            controller: function ($scope, $element, $attrs) {
                this.deletePreview = function (preview) {
                    var imagePreview = $scope[$attrs.myImagePreviewModel];
                    var previewIndex = imagePreview.indexOf(preview);
                    if (previewIndex != -1) {
                        imagePreview.splice(previewIndex, 1);
                    }
                }
            },
            compile: function () {
                return {
                    pre: function postLink($scope, $ele, attr) {
                        var imagePreview = $scope[attr.myImagePreviewModel] = [];
                        var unwatch = $scope.$watch(attr.myImagePreview, function (newFiles, oldFiles) {
                            if (newFiles && newFiles.length) {
                                for (var i = 0; i < newFiles.length; i++) {
                                    imagePreview.push(newFiles[i]);
                                }
                            }
                        });
                        $scope.$on('$destroy', function () {
                            unwatch();
                        });
                    }
                }
            }
        }
    })
    .directive('myImagePreviewSingle', function ($injector) {
        return {
            restrict: 'A',
            require: '^myImagePreview',
            compile: function () {
                var Upload = $injector.get('Upload');
                return function postLinkFn($scope, $ele, attr, ctrl) {
                    var file = $scope.preview;

                    $scope.showDelIconFn = function () {
                        $scope.showDelIcon = true;
                    };

                    $scope.hideDelIconFn = function () {
                        $scope.showDelIcon = false;
                    };

                    $scope.deletePreview = function () {
                        ctrl.deletePreview(file);
                        $ele.remove();
                    };

                    Upload.dataUrl(file).then(function (result) {
                        $scope.dataUrl = result;
                    });
                }

            }
        }
    });
